<?php

namespace app\ask\controller;

use think\Controller;

class Signin extends Controller
{
  public function __construct()
  {
    parent::__construct();

    $this->model = model('Post.Signin');
    $this->BusinessModel = model('Business.Business');
  }

  // 签到的方法
  public function add()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数
      $busid = $this->request->param('busid', 0, 'trim');

      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      // 判断今天是否有签到过
      // whereTime：是thinkphp5里面的一个方法
      $check = $this->model->where(['busid' => $busid])->whereTime('createtime', 'today')->find();

      if ($check) {
        $this->error('您今天已签到');
        exit;
      }

      /**
       * 签到表（插入）
       * 用户表（更新积分）
       */

      //签到
      $this->BusinessModel->startTrans();
      $this->model->startTrans();

      //插入签到表
      $SignStatus = $this->model->save(['busid' => $busid]);

      if ($SignStatus === FALSE) {
        $this->error($this->model->getError());
        exit;
      }

      //用户积分
      $point = $business['point'];
      // 判断用户的积分是否大于等于0
      $point = intval($point) >= 0 ? intval($point) : 0;
      $point += 10;

      // 组装数据
      $BusData = [
        'id' => $busid,
        'point' => $point
      ];

      //更新用户积分
      $BusStatus = $this->BusinessModel->isUpdate(true)->save($BusData);

      if ($BusStatus === FALSE) {
        $this->model->rollback();
        $this->error($this->BusinessModel->getError());
        exit;
      }

      if ($SignStatus === FALSE || $BusStatus === FALSE) {
        $this->BusinessModel->rollback();
        $this->model->rollback();
        $this->error('签到失败');
        exit;
      } else {
        $this->model->commit();
        $this->BusinessModel->commit();
        $this->success('签到成功');
        exit;
      }
    }
  }

  // 显示签到的方法
  public function index()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数
      $busid = $this->request->param('busid', 0, 'trim');
      $date = $this->request->param('date', date("Y-m"), 'trim');

      // 判断
      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      // 找到本月的开始时间和结束时间
      $start = date("Y-m-01", strtotime($date));
      $end = date("Y-m-t", strtotime($date));

      // 查询现在的时间是否在这个区间内
      $list = $this->model
        ->where(['busid' => $busid])
        ->whereTime('createtime', 'between', [$start, $end])
        ->order('createtime', 'asc')
        ->select();

      if (!$list) {
        $this->error('本月暂无签到记录');
        exit;
      }

      $this->success('成功查询签到记录', null, $list);
      exit;
    }
  }
}
